package cn.edu.bupt.webapi.demo.controller;

import cn.edu.bupt.webapi.demo.entity.Todo;
import cn.edu.bupt.webapi.demo.exception.NotFoundException;
import cn.edu.bupt.webapi.demo.mapper.TodoMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import java.util.List;

@RestController
//@Tag注解用来定义一组API
@Tag(name = "TodoController v1", description = "利用HTTP状态码表示操作结果状态的控制器")
@RequestMapping("/api/v1/todos")
public class TodoController {

    @Resource
    TodoMapper todoMapper;

    //@Operation用来对API添加说明
    @Operation(summary = "获取todolist", description = "返回值为全部的todolist")
    @GetMapping(path = "/", produces = "application/json")
    @ResponseStatus(HttpStatus.OK)
    public List<Todo> listAll(){
        List<Todo> todos = todoMapper.selectList(null);
        return todos;
    }

    @Operation(summary = "根据id获取相应的todo", description = "如果不存在，返回状态码为404")
    @GetMapping(path = "/{id}", produces = "application/json")
    @ResponseStatus(HttpStatus.OK)
    public Todo getById(@PathVariable("id") Long id) {
        Todo todo = todoMapper.selectById(id);
        if (todo == null) {
            throw new NotFoundException();
        }
        return todo;
    }

    @Operation(summary = "添加新的todo", description = "创建成功，返回状态码201")
    @PostMapping(path = "/", consumes = "application/json", produces = "application/json")
    @ResponseStatus(HttpStatus.CREATED)
    public Todo create(@RequestBody Todo todo) {
        todoMapper.insert(todo);
        return todo;
    }

    @Operation(summary = "根据id删除todo")
    @DeleteMapping(path = "/{id}")
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable Long id) {
        if(todoMapper.deleteById(id) <=0){
            throw new NotFoundException();
        }
        return;
    }

    @Operation(summary = "更新todo", description = "如果不存在，则返回状态码404")
    @ResponseStatus(HttpStatus.OK)
    @PutMapping(path = "/{id}", consumes = "application/json", produces = "application/json")
    public Todo update(@PathVariable Long id, @RequestBody Todo todo) {
        todo.setId(id);
        if (todoMapper.updateById(todo) <= 0) {
            throw new NotFoundException();
        }
        return todo;
    }
}
